import logging

from src.graph.talent_model import Talent
from src.supabase_db.supabase import DBConnection

logger = logging.getLogger(__name__)


async def save_tenant(talent: Talent):
    """保存简历"""
    try:
        db_conn = DBConnection()
        client = await db_conn.client

        talent_dict = talent.model_dump(exclude_none=True)
        existing = await (client.table("talents").select("*")
                          .eq("user_id", talent.user_id)
                          .eq("project_id", talent.project_id)
                          .eq("name", talent.name)
                          .execute())
        update_result = None
        if existing.data:
            # 修改
            id = existing.data[0]["id"]
            update_result = await client.table('talents').update(talent_dict).eq("id", id).execute()
        else:
            update_result = await client.table('talents').insert(talent_dict).execute()

        if hasattr(update_result, 'data') and update_result.data:
            return update_result.data[0]
        else:
            logger.error(f"Failed to save talents {talent.project_id} name in database. Update result: {update_result}")

    except Exception as e:
        logger.error(f"Error in background naming task for talents {talent.project_id}: {str(e)}")
    finally:
        logger.info(f"Finished background naming task for talents: {talent.project_id}")


async def get_tenants(project_id: str):
    """获取项目人才库列表"""
    db_conn = DBConnection()
    client = await db_conn.client
    response = await (client.table("talents").select("*")
                          .eq("project_id", project_id)
                          .execute())
    result = []
    if response.data:
        for item in response.data:
            talent = Talent(**item)
            result.append(talent)

    return result
